<template>
  <view class="city-page">
    <!-- 搜索框 -->
    <view class="search-box">
      <u-search
          v-model="keyword"
          placeholder="搜索城市"
          :show-action="false"
          :clearabled="true"
          @change="handleSearch"
      />
    </view>

    <!-- 当前定位城市 -->
    <view class="section current-city">
      <view class="section-title">当前定位城市</view>
      <view class="city-grid">
        <view class="city-item active" @click="selectCity(currentCity)">
          <text>{{ currentCity.name }}</text>
        </view>
        <view class="city-item" @click="getLocation">
          <text>重新定位</text>
        </view>
      </view>
    </view>


    <!-- 城市列表 -->
    <scroll-view
        class="city-list"
        scroll-y
        :scroll-into-view="scrollIntoView"
        @scroll="onScroll"
    >
      <!-- 热门城市 -->
      <view class="section hot-cities" v-if="hotCities.length">
        <view class="section-title">热门城市</view>
        <view class="city-grid">
          <view
              class="city-item"
              v-for="city in hotCities"
              :key="city.code"
              @click="selectCity(city)"
          >
            <text>{{ city.name }}</text>
          </view>
        </view>
      </view>
      <view
          v-for="group in filteredGroups"
          :key="group.initial"
          :id="'index-' + group.initial"
      >
        <view class="index-title">{{ group.initial }}</view>
        <view
            class="city-item"
            v-for="city in group.cities"
            :key="city.code"
            @click="selectCity(city)"
        >
          {{ city.name }}
        </view>
      </view>
    </scroll-view>

    <!-- 右侧索引 -->
    <view class="index-list">
      <view
          class="index-item"
          v-for="initial in initials"
          :key="initial"
          @click="scrollToIndex(initial)"
      >
        {{ initial }}
      </view>
    </view>
  </view>
</template>

<script>
import {hotCities,  cityGroups } from './cities.js'

export default {
  data() {
    return {
      keyword: '',
      scrollIntoView: '',
      currentCity: {
        name: '定位中...',
        code: ''
      },
      hotCities: JSON.parse(JSON.stringify(hotCities)),
      cityGroups: JSON.parse(JSON.stringify(cityGroups)),
      filteredGroups: []
    }
  },
  onLoad() {
    this.filteredGroups = this.cityGroups
    this.getLocation()
  },
  computed: {
    initials() {
      return this.cityGroups.map(group => group.initial)
    }
  },
  methods: {
    // 获取定位
    getLocation() {
      this.currentCity = {
        name: '定位中...',
        code: ''
      }

      uni.getLocation({
        type: 'gcj02',
        success: res => {
          console.log(res)
          this.getCityFromLocation(res.latitude, res.longitude)
        },
        fail: err => {
          console.log(err)
          // 定位失败
          this.currentCity = {
            name: '定位失败',
            code: ''
          }
          uni.showToast({
            title: '定位失败，请检查定位权限',
            icon: 'none'
          })
        }
      })
    },

    // 根据经纬度获取城市
    getCityFromLocation(latitude, longitude) {
      uni.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        data: {
          location: `${latitude},${longitude}`,
          key: 'VQKBZ-WWSLG-EJQQI-IFK6O-E7CC6-N2BQE', // 需要替换为实际的腾讯地图 key
          get_poi: 0
        },
        success: res => {
          if (res.data.status === 0) {
            const cityName = res.data.result.address_component.city
            // 去掉"市"字
            const name = cityName.replace(/市$/, '')

            // 查找对应的城市代码
            for (const group of this.cityGroups) {
              const city = group.cities.find(c => c.name === name)
              if (city) {
                this.currentCity = {
                  name: name,
                  code: city.code
                }
                return
              }
            }

            // 如果在城市列表中找不到，只保存城市名
            this.currentCity = {
              name: name,
              code: ''
            }
          } else {
            this.currentCity = {
              name: '定位失败',
              code: ''
            }
          }
        },
        fail: () => {
          this.currentCity = {
            name: '定位失败',
            code: ''
          }
        }
      })
    },
    handleSearch(value) {
      if (!value) {
        this.filteredGroups = this.cityGroups
        return
      }

      // 搜索城市
      this.filteredGroups = this.cityGroups.map(group => {
        return {
          initial: group.initial,
          cities: group.cities.filter(city =>
            city.name.toLowerCase().includes(value.toLowerCase())
          )
        }
      }).filter(group => group.cities.length > 0)
    },
    selectCity(city) {
      if (!city.code) {
        uni.showToast({
          title: '定位失败，请检查定位权限',
          icon: 'none'
        })
        return
      }
      // 选择城市后的处理
      uni.setStorageSync('selectedCity', city)
      uni.$emit('citySelected', city)
      uni.navigateBack()
    },
    scrollToIndex(initial) {
      this.scrollIntoView = 'index-' + initial
    },
    onScroll(e) {
      // 可以添加滚动时的索引高亮逻辑
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: hidden;
}
.city-page {
  height: 100%;
  overflow: hidden;
  background: #F5F5F5;
  position: relative;
  display: flex;
  flex-direction: column;
}

.search-box {
  padding: 20rpx;
  background: #fff;
}

.section {
  margin: 20rpx 0;
  padding: 20rpx;
  background: #fff;

  .section-title {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 20rpx;
  }
}

.city-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;

  .city-item {
    width: calc((100% - 60rpx) / 4);
    height: 64rpx;
    background: #F5F5F5;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #333;

    &.active {
      background: #E6F7F4;
      color: #04C8AE;
    }

    &:active {
      opacity: 0.8;
    }
  }
}

.city-list {
  height: calc(100vh - 400rpx);
  padding: 0 32rpx;
  background: #fff;

  .index-title {
    padding: 16rpx 0;
    font-size: 28rpx;
    color: #999;
    background: #F5F5F5;
  }

  .city-item {
    padding: 32rpx 0;
    font-size: 32rpx;
    color: #333;
    border-bottom: 1rpx solid #EEEEEE;
  }
}

.index-list {
  position: fixed;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 32rpx;
  padding: 16rpx 8rpx;

  .index-item {
    padding: 8rpx 12rpx;
    font-size: 24rpx;
    color: #fff;
    text-align: center;
  }
}
</style>
